﻿using CefSharp;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace WebBrowserTest
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            //这个一定要开启，否则注入C#的对象无效
            CefSharp.CefSharpSettings.LegacyJavascriptBindingEnabled = true;

            //构造要注入的对象，参数为当前线程的调度上下文
            var obj = new CSObj(System.Threading.SynchronizationContext.Current);
            //注册C#对象
            browser.JavascriptObjectRepository.Register("cs", obj, false, CefSharp.BindingOptions.DefaultBinder);
            // 屏蔽右键菜单
            browser.MenuHandler = new MenuHandler();
            // JS弹出保存框的支持
            browser.DownloadHandler = new DownloadHandler();
            //html的路径一定要是绝对路径
            string htmlPath = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "test.html");
            browser.Address = htmlPath;

            Unloaded += (sender, e) =>
            {
                Cef.Shutdown();
            };
        }

        private void btnShowDev_Click(object sender, RoutedEventArgs e)
        {
            browser.ShowDevTools();
        }

        private void btnCallJS_Click(object sender, RoutedEventArgs e)
        {
            browser.GetMainFrame().ExecuteJavaScriptAsync("alert('cs')");
        }
    }

}
